var app = angular.module("app", ["ui.router", "PublicModule", "ngCookies", 'Encrypt']);



// file对象
app.directive("fileModel", ["$parse", function ($parse) {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            element.bind("change", function () {
                scope.$apply(function () {
                    modelSetter(scope, element[0].files[0]);
                    // console.log( scope );
                })
            })
        }
    }
}])

app.service("fileUpload", ["$http", '$cookieStore', function ($http, $cookieStore) {
    this.uploadFileToUrl = function (file, uploadUrl, type) {
        var fd = new FormData();
        fd.append("file", file)
        fd.append('type', type)
        fd.append('id', $cookieStore.get('login').id)
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: { "Content-Type": undefined }
        }).then(function successCallback(response) {
            if (response.data.status == 101) {
                $timeout(function(){                
                    $scope.Name = response.data.data.name;
                    $scope.idNum = response.data.data.cert_num;
                },60)
            } else if (response.data.status == 102) {
                $.alert({
                    title: '错误',
                    text: response.data.data,
                });
            }
            console.log(response.data)
            // alert()
            // document.write(response.data)
        }, function errorCallback(response) {
            $.alert({
                title: '错误',
                text: '此图片错误，请重新上传',

            });
        });

    }
}])
app.service("upHouse", ["$http", '$cookieStore','$state', function ($http, $cookieStore,$state) {
    this.uploadFileToUrl = function (uploadUrl,file) {
        var fd = new FormData();

        fd.append("title", file.title);
        fd.append("name", file.name);
        fd.append("tel", file.tel);
        fd.append("price", file.day_price);
        fd.append("lng", file.lng);
        fd.append("lat", file.lat);
        fd.append("address", file.address);
        fd.append("style", file.style);
        fd.append("type", file.type);
        fd.append("size", file.size);
        for(let i=0;i<file.img.length;i++){            
            fd.append("img"+i+"",file.img[i]);
        }
 console.log(file.img)
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: { "Content-Type": undefined }
        }).then(function successCallback(response) {
            if (response.data.status == 101) {
                $.alert({
                    title: '提示',
                    text: '发布成功，等待审核',
                    onOK: function () {
                        $state.go('index')
                    }
                });
            } else if (response.data.status == 102) {
                $.alert({
                    title: '错误',
                    text: response.data.data,

                });
            }else{
                $.alert({
                    title: '错误',
                    text: response.data.data,

                });
            }

        }, function errorCallback(response) {
            $.alert({
                title: '错误',
                text: '此图片错误，请重新上传',

            });
        });

    }
}])

// 封装的轮播插件
app.directive('container', [function (val) {
    return {
        restrict: 'E',
        scope: {
            data: '='
        },
        template: `<div class="swiper-container">
            <div class="swiper-wrapper">
                <div class="swiper-slide" ng-repeat="swiperImg in data track by $index"><img ng-src="{{'http://www.andthink.cn/gongyu/'+swiperImg.img}}" alt=""></div>    
            </div>
            <div class="swiper-pagination"></div>   
        </div>`,
        replace: true,
        link: function ($scope, element, attrs, $window) {
            $(element).height(window.screen.width / 2.33)
            // 首页轮播图启动
            var mySwiper = new Swiper('.swiper-container', {
                pagination: '.swiper-pagination',
                paginationClickable: true,
                longSwipesRatio: 0.3,
                touchRatio: 1,
                observer: true,//修改swiper自己或子元素时，自动初始化swiper
                observeParents: true,//修改swiper的父元素时，自动初始化swiper
            });

        }
    }
}])

// 封装的Tab
app.directive('tab', ['$http', '$cookieStore', function ($http, $cookieStore) {
    return {
        restrict: 'E',
        template: `<div class='AllNav' ng-init="local=true">
            <span   ng-click="cityColl()">{{showCity?showCity:"请选择"}}  ▼  </span>
            <ul class="addressBox" ng-show="!local">
                <li ng-repeat="city in city track by $index" ng-click="collAddress(city.id,city.type,$index)">
                    {{city.name}}
                </li>    
            </ul>
            <div class='coll'>
                <img src='../gy/images/icon/magnifier.png' ng-click="collData()"/>
                <input type='text' ng-model="collD"/>
            </div>
            <div class='userImg' ui-sref='center({id:"center"})'>
                <img src='../gy/images/icon/user.png'/>
            </div>
        <div>        
        `,
        replace: true,
        controller: function ($scope) {
            // 定位数据
            if (!$cookieStore.get('cityName')) {
                $scope.showCity = null
            } else {
                console.log("ksk")
                $scope.showCity = $cookieStore.get('cityName').name
                // console.log($cookieStore.get('cityName'))
            }
            // 选择城市
            $scope.local=false;
            $scope.cityColl = function () {
                $scope.local = !$scope.local
                if (!$scope.local) {
                    $http({
                        method: 'post',
                        url: $scope.httptit + '/index/index/index.html',
                        data: {
                            do: 'index'
                        },
                        dataType: 'json',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: $scope.changeData
                    }).then(function successCallback(response) {
                        $scope.names = response.data;
                        $scope.city = response.data.data.area;
                    }, function errorCallback(response) {
                    });
                    // alert('定位失败，请刷新后重试')
                }
            }
            // 选择城市
            $scope.collAddress = function (v, t, index) {
                $http({
                    method: 'post',
                    url: $scope.httptit + '/index/index/index.html',
                    data: {
                        id: v,
                        do: 'city',
                        type: t,
                    },
                    dataType: 'json',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    transformRequest: $scope.changeData
                }).then(function successCallback(response) {
                    $scope.names = response.data;
                    if (response.data.status == 102) {
                        $scope.showCity = $scope.city[index].name;
                        console.log($scope.city[index].name)
                        $cookieStore.put('cityName', { id: $scope.city[index].id, name: $scope.city[index].name });
                        $scope.local = !$scope.local;

                        return
                    } else {
                        $scope.city = response.data.data
                    }
                }, function errorCallback(response) {
                    console.log(response)
                    // 请求失败执行代码
                });
            }
            // 搜索数据
            $scope.collData = function () {
                if ($cookieStore.get('cityName')) {
                    $http({
                        method: 'post',
                        url: $scope.httptit + '/index/house/lst.html',
                        data: {
                            style: $cookieStore.get('houseStyle').id,
                            lng:$cookieStore.get('lng&lat').lng,
                            lat:$cookieStore.get('lng&lat').lng,
                            count: 5,
                            page: 1,
                            order: 1,
                            id: $cookieStore.get('cityName').id,
                            keyword: $scope.collD
                        },
                        dataType: 'json',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: $scope.changeData
                    }).then(function successCallback(response) {
                        if (response.data.status == 102) {
                            console.log($scope.PartData)
                            $.alert({
                                title: '提示',
                                text: '未检测到数据，请定位后重试',
                                onOK: function () {
                                    //点击确认
                                }
                            });
                        }
                        if (response.data.status == 101) {
                            $scope.PartData = response.data.data;
                            console.log(response.data.data)
                        }

                    }, function errorCallback(response) {
                        console.log(response)

                    });
                } else {
                    $http({
                        method: 'post',
                        url: $scope.httptit + '/index/house/lst.html',
                        data: {
                            style: $cookieStore.get('houseStyle').id,
                            // lng:$cookieStore.get('lng&lat').lng,
                            // lat:$cookieStore.get('lng&lat').lng,
                            lng: 123.1112232,
                            lat: 113.223,
                            count: 5,
                            page: 1,
                            order: 1,
                            keyword: $scope.collD
                        },
                        dataType: 'json',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: $scope.changeData
                    }).then(function successCallback(response) {
                        if (response.data.status == 102) {
                            console.log($scope.PartData)
                            $.alert({
                                title: '提示',
                                text: '未检测到数据，请定位后重试',
                                onOK: function () {
                                    //点击确认
                                }
                            });
                        }
                        if (response.data.status == 101) {
                            $scope.PartData = response.data.data;
                            console.log(response.data.data)
                        }

                    }, function errorCallback(response) {
                        console.log(response)

                    });
                }

            }

        }
    }
}])
// 高德地图
app.directive('gaodeMap', ['$http', '$cookieStore', function ($http, $cookieStore) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div id="container"></div>',
        scope: {
            options: '='
        },
        link: function ($scope, elem, attr) {
            $scope.dayHosueAdd = '';

            //  初始化高德地图   
            $scope.map = new AMap.Map("container", {
                resizeEnable: true,
                center: [116.397428, 39.90923],//地图初始化地点
                zoom: 18 //地图显示的缩放级别
            });

            // 浏览器定位到当前
            $scope.map.plugin('AMap.Geolocation', function () {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 30000,          //超过10秒后停止定位，默认：无穷大
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    buttonPosition: 'RB'
                });
                $scope.map.addControl(geolocation);
                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
                AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
            });
            //解析定位结果
            function onComplete(data) {
                var str = ['定位成功'];
                str.push('经度：' + data.position.getLng());
                str.push('纬度：' + data.position.getLat());
                if (data.accuracy) {
                    str.push('精度：' + data.accuracy + ' 米');
                }//如为IP精确定位结果则没有精度信息
                str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
                console.log(str.join('<br>'));
            }
            //解析定位错误信息
            function onError(data) {
                console.log('定位失败，请刷新后重试')
            }

            // 自定义标注
            console.log($scope.httptit)
            var markers = [];
            $http({
                method: 'post',
                url: 'http://www.andthink.cn/gongyu/index.php/index/house/range.html',
                data: {
                    lng: $cookieStore.get('lng&lat').lng,
                    lat: $cookieStore.get('lng&lat').lng,
                },
                dataType: 'json',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: $scope.changeData
            }).then(function successCallback(response) {
                console.log(response.data)
                //使用请求到的经纬度自定义标注
                response.data.data.forEach(function () {
                    markers = [{
                        icon: '../images/map.png',
                        position: [response.data.data.lng, response.data.data.lat]
                    }]
                })
                markers.forEach(function (marker) {
                    new AMap.Marker({
                        map: $scope.map,
                        icon: marker.icon,
                        position: [marker.position[0], marker.position[1]],
                        offset: new AMap.Pixel(-12, -36)
                    });
                });
            }, function errorCallback(response) {
                console.log(response)
            });
            //  S 自定义标注               
            // $scope.map.clearMap();  // 清除地图覆盖物
            // 自定义标注物的图标以及经纬度
            // var markers = [{
            //     icon: '../images/map.png',
            //     position: [116.205467, 39.907761]
            // }, {
            //     icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b2.png',
            //     position: [116.368904, 39.913423]
            // }, {
            //     icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b3.png',
            //     position: [116.305467, 39.807761]
            // }];
            // 添加一些分布不均的点到地图上,地图上添加三个点标记，作为参照

        }
    }

}]);



// 高德地图
app.directive('addMap', ['$cookieStore', function ($cookieStore) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div id="container"></div>',
        scope: {
            options: '='
        },
        link: function ($scope, elem, attr) {
            $scope.dayHosueAdd = '';

            //  初始化高德地图  
            $scope.map = new AMap.Map("container", {
                resizeEnable: true,
                center: [116.397428, 39.90923],//地图初始化地点
                zoom: 23 //地图显示的缩放级别
            });

            // 浏览器定位到当前
            $scope.map.plugin('AMap.Geolocation', function () {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                    convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                    showButton: true,        //显示定位按钮，默认：true
                    buttonPosition: 'RB',    //定位按钮停靠位置，默认：'LB'，左下角
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                    showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
                    panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                    zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                });
                $scope.map.addControl(geolocation);
                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
                AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
            });
            //解析定位结果
            function onComplete(data) {
                var str = ['定位成功'];
                str.push('经度：' + data.position.getLng());
                str.push('纬度：' + data.position.getLat());
                if (data.accuracy) {
                    str.push('精度：' + data.accuracy + ' 米');
                }//如为IP精确定位结果则没有精度信息
                str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));

            }
            //解析定位错误信息
            function onError(data) {
                console.log('定位失败，请刷新后重试')
            }


            $scope.map.on('click', function (e) {
                lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()]; //已知点坐标
                // $scope.lnglat=lnglatXY;
                $cookieStore.put('lnglat', { lng: e.lnglat.getLng(), lat: e.lnglat.getLat() })
                $scope.regeocoder(lnglatXY);
            });
            // 经纬度反编译
            $scope.regeocoder = function (lnglatXY) {  //逆地理编码
                var geocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });
                geocoder.getAddress(lnglatXY, function (status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        $scope.dayHosueAdd = result.regeocode.formattedAddress;
                        $('#houseADD').html(result.regeocode.formattedAddress)

                    }

                });
                $scope.map.setFitView();
            }
        }

    }

}]);


// 路由文件
app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('index', {
            url: '/index',
            templateUrl: '/gy/views/index.html',
            controller: 'homeCtrl',
            params: {
                title: "共享公寓"
            }
        })  // 主页路由
        .state('longRend', {
            url: '/longRend?id',
            templateUrl: '/gy/views/longRend.html',
            controller: 'HousePart',
            params: {
                title: "长租房",
                id: null
            }

        })  //长租路由
        .state('longDesc', {
            url: '/longDesc?id',
            templateUrl: '/gy/views/longDesc.html',
            controller: 'longRend',
            params: {
                title: null,
                id: null
            }
        })  //发布房源
        .state('dayRend', {
            url: '/dayRend',
            templateUrl: '/gy/views/dayRend.html',
            controller: 'indexCtrl',
            params: {
                title: "日租房"
            }

        })  //日租路由
        .state('mapRend', {
            url: '/mapRend',
            templateUrl: '/gy/views/mapRend.html',
            controller: 'indexCtrl',
            params: {
                title: "地图找房"
            }
        })  //地图找房
        .state('tenancyRend', {
            url: '/tenancyRend',
            templateUrl: '/gy/views/tenancyRend.html',
            controller: 'indexCtrl',
            params: {
                title: "房屋出售列表"
            }

        })  //房屋出售列表
        .state('soldRend', {
            url: '/soldRend',
            templateUrl: '/gy/views/soldRend.html',
            controller: 'indexCtrl',
            params: {
                title: "房屋出售列表"
            }

        })  //房屋出售列表
        .state('recruitRend', {
            url: '/recruitRend?id',
            templateUrl: '/gy/views/recruitRend.html',
            controller: 'indexCtrl',
            params: {
                title: "房东招募",
                id: null

            }

        })  //房东招募
        .state('partRend', {
            url: '/partRend?id&tit',
            templateUrl: '/gy/views/partRend.html',
            controller: 'partRend',
            params: {
                tit: null,
                id: null
            }

        })  //房间详情 
        .state('reserRend', {
            url: '/reserRend?id&title',
            templateUrl: '/gy/views/reserRend.html',
            controller: 'partRend',
            params: {
                title: null,
                id: null
            }

        })  //订单内容  
        .state('order', {
            url: '/order?id&title',
            templateUrl: '/gy/views/order.html',
            controller: 'order',
            params: {
                title: null,
                id: null
            }
        })  //订单支付
        .state('center', {
            url: '/center?id',
            templateUrl: '/gy/views/center.html',
            controller: 'indexCtrl',
            params: {
                title: "个人中心",
                id: null
            }
        })  //个人中心
        .state('userData', {
            url: '/userData?id',
            templateUrl: '/gy/views/userData.html',
            controller: 'userdata',
            params: {
                title: "详细资料",
                id: null
            }
        })  //详细资料
        .state('MsgList', {
            url: '/MsgList?id',
            templateUrl: '/gy/views/MsgList.html',
            controller: 'indexCtrl',
            params: {
                title: "消息列表",
                id: null
            }
        })  //消息列表
        .state('orderList', {
            url: '/orderList?id',
            templateUrl: '/gy/views/orderList.html',
            controller: 'indexCtrl',
            params: {
                title: "我的订单",
                id: null
            }
        })  //我的订单    
        .state('contract', {
            url: '/contract',
            templateUrl: '/gy/views/contract.html',
            controller: 'indexCtrl',
            params: {
                title: "租赁合同"
            }
        })  //租赁合同
        .state('collect', {
            url: '/collect?id',
            templateUrl: '/gy/views/collect.html',
            controller: 'indexCtrl',
            params: {
                title: "我的收藏",
                id: null
            }
        })  //我的收藏
        .state('feedback', {
            url: '/feedback?id',
            templateUrl: '/gy/views/feedback.html',
            controller: 'indexCtrl',
            params: {
                title: "意见反馈",
                id:null
            }
        })  //意见反馈
        .state('loginClean', {
            url: '/loginClean',
            templateUrl: '/gy/views/loginClean.html',
            controller: 'cleanCtrl',
            params: {
                title: "保洁登录"
            }
        })  //保洁登录
        .state('forClean', {
            url: '/forClean',
            templateUrl: '/gy/views/forClean.html',
            controller: 'cleanCtrl',
            params: {
                title: "待打扫的房间"
            }
        })  //保洁登录  
        .state('loginLand', {
            url: '/loginLand',
            templateUrl: '/gy/views/loginLand.html',
            controller: 'landCtrl',
            params: {
                title: "房东登录"
            } 
        })  //房东登录
        .state('landLits', {
            url: '/landLits',
            templateUrl: '/gy/views/landLits.html',
            controller: 'landCtrl',
            params: {
                title: "房间列表"
            }
        })  //房间列表
        .state('postHouse', {
            url: '/postHouse',
            templateUrl: '/gy/views/postHouse.html',
            controller: 'indexCtrl',
            params: {
                title: "发布房源"
            }
        })  //发布房源
        .state('commentList', {
            url: '/commentList?houseid&title',
            templateUrl: '/gy/views/commentList.html',
            controller: 'indexCtrl',
            params: {
                title: null,
                houseid: null
            }
        })  //查看评论
        .state('collList', {
            url: '/collList',
            templateUrl: '/gy/views/longRend.html',
            controller: 'indexCtrl',
            params: {
                title: "搜索",
                id: 'null'
            }
        })  //查看评论
        .state('comment', {
            url: '/comment?id',
            templateUrl: '/gy/views/feedback.html',
            controller: 'indexCtrl',
            params: {
                title: "评价",
                id: null
            }
        })  //评论
        .state('about', {
            url: '/about',
            templateUrl: '/gy/views/about.html',
            controller: 'indexCtrl',
            params: {
                title: "关于我们",
            }
        })  //评论  
        .state('backPass', {
            url: '/backPass',
            templateUrl: '/gy/views/backPass.html',
            controller: 'landCtrl',
            params: {
                title: "找回密码",
            }
        })  //评论
    $urlRouterProvider.otherwise('/index');

}]);
